import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ui/api/config.dart';
import 'package:ui/api/db.dart';
import 'package:ui/api/router.dart';
import 'package:ui/view/setting/logic.dart';

import 'state.dart';

class HomeLogic extends GetxController {
  final HomeState state = HomeState();

  final SettingLogic settingLogic = Get.put(SettingLogic());

  late Widget topPricesShow = GridView.builder(
      // shrinkWrap: true,
      // 设置不可滚动
      // physics: const NeverScrollableScrollPhysics(),
      itemCount: settingLogic.topicView.length,
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3, // 条目个数
        mainAxisSpacing: 5, // 竖间距
        crossAxisSpacing: 5, // 横间距
      ),
      itemBuilder: (_, int p) {
        return GestureDetector(
          onTap: () {
            String str = settingLogic.topicView[p];
            debugPrint("导航到具有参数的页面->$str");
            // 导航到具有参数的页面
            Get.toNamed(Routes.updatePrices, arguments: str);
          },
          child: Container(
            height: 80,
            alignment: Alignment.center,
            color: Colors.lightBlue,
            child: FutureBuilder(
                future: getPrices(settingLogic.topicView[p]),
                builder: (ctx, snap) {
                  if (snap.connectionState == ConnectionState.done) {
                    return Text(
                      "${settingLogic.topicView[p]} \n ${snap.data.toString()}",
                      style: const TextStyle(color: Colors.white, shadows: [
                        Shadow(color: Colors.black, offset: Offset(.5, .5), blurRadius: 2),
                      ]),
                    );
                  } else {
                    return const CircularProgressIndicator();
                  }
                }),
          ),
        );
      });

  late RxList<Widget> listtile = RxList<Widget>([]);

  getPrices(String topic) async {
    var jsonmag = await config.apihttp.getmsg(config.settingLogic.uid.value, topic);
    return jsonmag['msg'];
  }

  // 获取档案列表
  getProfileList() async {
    // 先清空列表
    listtile.clear();
    List proflleList = await db.queryProfile();
    for (var profile in proflleList) {
      Profile dx = Profile.fromMap(profile);
      listtile.add(showLabel(dx));
    }
  }

  @override
  void onReady() {
    super.onReady();
    debugPrint("Home页面 -> onReady");
    // 延迟3秒后执行打印操作
    Future.delayed(const Duration(seconds: 3), () {
      getProfileList();
    });
  }

  // 档案显示控件
  showLabel(dx) => Dismissible(
        key: ValueKey(dx.id),
        background: Container(
          color: Colors.green,
          alignment: const Alignment(-0.9, 0),
          child: const Icon(Icons.check),
        ),
        secondaryBackground: Container(
          color: Colors.red,
          alignment: const Alignment(-0.9, 0),
          child: const Icon(
            Icons.delete_outline,
            color: Colors.white,
          ),
        ),
        // 确认回调
        confirmDismiss: (e) async {
          // 从右往左滑
          if (e == DismissDirection.endToStart) {
            // todo 从数据库删除当前档案
          }
          // 从左往右滑
          if (e == DismissDirection.startToEnd) {
            // todo 更改付款状态
          }
          return false;
        },
        // 消失回调
        onDismissed: (d) {},
        child: ListTile(
          onTap: () {
            Get.toNamed(Routes.addArchives, arguments: dx);
            debugPrint(dx.toMap().toString());
          },
          textColor: dx.is_checkout == 1 ? Colors.red : Colors.blue,
          title: Text(dx.name),
          subtitle: Text(dx.time),
          trailing: RichText(
            textAlign: TextAlign.end,
            text: TextSpan(
              style: TextStyle(fontSize: 20, color: dx.is_checkout == 1 ? Colors.red : Colors.blue),
              children: [
                const TextSpan(text: "RMB: "),
                TextSpan(text: dx.rmb),
              ],
            ),
          ),
        ),
      );
}
